<template>
  <view class="scan-container">
    <!-- H5扫码区域 -->
    <!-- #ifdef H5 -->
    <view class="h5-scan-area">
      <!-- 相机预览区域 -->
      <view class="camera-preview" v-if="showCamera">
        <video id="video" ref="video" :src="videoSrc" class="video-preview" muted autoplay playsinline
          webkit-playsinline></video>
        <canvas id="canvas" ref="canvas" class="scan-canvas"
          :style="{ width: canvasWidth + 'px', height: canvasHeight + 'px' }"></canvas>
      </view>

      <!-- 扫码框 -->
      <view class="scan-frame">
        <view class="scan-box">
          <!-- 四个角的装饰 -->
          <view class="corner corner-tl"></view>
          <view class="corner corner-tr"></view>
          <view class="corner corner-bl"></view>
          <view class="corner corner-br"></view>

          <!-- 扫描线 -->
          <view class="scan-line" v-if="isScanning"></view>
        </view>

        <view class="scan-hint">将二维码放入框内，即可自动扫描</view>
      </view>

      <!-- 底部操作按钮 -->
      <view class="scan-actions">
        <view class="action-btn" @click="startCamera" v-if="!showCamera">
          <view class="btn-icon">
            <u-icon name="camera" size="48" color="#ffffff"></u-icon>
          </view>
          <view class="btn-text">打开相机</view>
        </view>
        <view class="action-btn" @click="stopCamera" v-if="showCamera">
          <view class="btn-icon">
            <u-icon name="close" size="48" color="#ffffff"></u-icon>
          </view>
          <view class="btn-text">关闭相机</view>
        </view>
        <view class="action-btn" @click="chooseImage">
          <view class="btn-icon">
            <u-icon name="photo" size="48" color="#ffffff"></u-icon>
          </view>
          <view class="btn-text">选择图片</view>
        </view>
        <view class="action-btn" @click="goBack">
          <view class="btn-icon">
            <u-icon name="arrow-left" size="48" color="#ffffff"></u-icon>
          </view>
          <view class="btn-text">返回</view>
        </view>
      </view>
    </view>
    <!-- #endif -->

    <!-- 小程序扫码区域 -->
    <!-- #ifdef MP-WEIXIN -->
    <view class="mp-scan-area">
      <view class="scan-frame">
        <view class="scan-box">
          <!-- 四个角的装饰 -->
          <view class="corner corner-tl"></view>
          <view class="corner corner-tr"></view>
          <view class="corner corner-bl"></view>
          <view class="corner corner-br"></view>

          <view class="scan-icon">
            <u-icon name="scan" size="120" color="#74b9ff"></u-icon>
          </view>
        </view>

        <view class="scan-hint">点击下方按钮开始扫码</view>
      </view>

      <!-- 扫码按钮 -->
      <view class="scan-actions">
        <view class="scan-button" @click="startScan">
          <view class="btn-text">开始扫码</view>
        </view>
        <view class="back-button" @click="goBack">
          <view class="btn-text">返回</view>
        </view>
      </view>
    </view>
    <!-- #endif -->
  </view>
</template>

<script>
// #ifdef H5
import jsQR from "jsqr";
// #endif

export default {
  data() {
    return {
      // 扫码类型
      scanType: "default",
      // H5相机相关
      showCamera: false,
      videoSrc: "",
      isScanning: false,
      canvasWidth: 300,
      canvasHeight: 300,
      // 扫码结果
      scanResult: "",
      // 定时器
      scanTimer: null,
    };
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.scanType = options.type || "default";
    // #ifdef H5
    this.initCamera();
    // #endif
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    this.cleanup();
  },

  methods: {
    /**
     * 返回上一页
     */
    goBack() {
      this.cleanup();
      uni.navigateBack({
        delta: 1,
      });
    },

    /**
     * 清理资源
     */
    cleanup() {
      // #ifdef H5
      if (this.scanTimer) {
        clearInterval(this.scanTimer);
        this.scanTimer = null;
      }
      this.stopCamera();
      // #endif
    },

    // #ifdef H5
    /**
     * 初始化相机
     */
    initCamera() {
      // 检查浏览器支持
      if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
        uni.showToast({
          title: "浏览器不支持相机功能",
          icon: "none",
        });
        return;
      }
    },

    /**
     * 启动相机
     */
    async startCamera() {
      try {
        uni.showLoading({
          title: "启动相机中...",
        });

        const stream = await navigator.mediaDevices.getUserMedia({
          video: {
            facingMode: "environment", // 后置摄像头
            width: { ideal: 1280 },
            height: { ideal: 720 },
          },
        });

        // 获取video元素
        const video = document.getElementById("video");
        if (video) {
          video.srcObject = stream;
          video.play();

          this.showCamera = true;
          this.isScanning = true;

          // 等待视频加载完成后开始扫码
          video.onloadedmetadata = () => {
            uni.hideLoading();
            this.startScanLoop();
          };
        }
      } catch (error) {
        uni.hideLoading();
        console.error("启动相机失败:", error);
        uni.showToast({
          title: "无法访问相机",
          icon: "none",
        });
      }
    },

    /**
     * 停止相机
     */
    stopCamera() {
      const video = document.getElementById("video");
      if (video && video.srcObject) {
        const tracks = video.srcObject.getTracks();
        tracks.forEach((track) => track.stop());
        video.srcObject = null;
      }
      this.showCamera = false;
      this.isScanning = false;

      if (this.scanTimer) {
        clearInterval(this.scanTimer);
        this.scanTimer = null;
      }
    },

    /**
     * 开始扫码循环
     */
    startScanLoop() {
      if (this.scanTimer) {
        clearInterval(this.scanTimer);
      }

      this.scanTimer = setInterval(() => {
        this.scanFrame();
      }, 500); // 每500ms扫描一次
    },

    /**
     * 扫描当前帧
     */
    scanFrame() {
      const video = document.getElementById("video");
      const canvas = document.getElementById("canvas");

      if (!video || !canvas || !this.isScanning) {
        return;
      }

      const context = canvas.getContext("2d");

      // 设置canvas尺寸
      canvas.width = video.videoWidth;
      canvas.height = video.videoHeight;

      // 绘制视频帧到canvas
      context.drawImage(video, 0, 0, canvas.width, canvas.height);

      // 获取图像数据
      const imageData = context.getImageData(0, 0, canvas.width, canvas.height);

      // 使用jsQR解析二维码
      const code = jsQR(imageData.data, imageData.width, imageData.height);

      if (code) {
        this.handleScanSuccess(code.data);
      }
    },

    /**
     * 从相册选择图片扫码
     */
    chooseImage() {
      const app = this;
      uni.chooseImage({
        count: 1,
        sizeType: ["original"],
        sourceType: ["album"],
        success(res) {
          app.analyzeImage(res.tempFilePaths[0]);
        },
        fail() {
          uni.showToast({
            title: "选择图片失败",
            icon: "none",
          });
        },
      });
    },

    /**
     * 分析图片中的二维码
     */
    analyzeImage(imagePath) {
      uni.showLoading({
        title: "识别中...",
      });

      // 创建图片对象
      const img = new Image();
      img.crossOrigin = "anonymous";

      img.onload = () => {
        // 创建canvas
        const canvas = document.createElement("canvas");
        const context = canvas.getContext("2d");

        canvas.width = img.width;
        canvas.height = img.height;

        // 绘制图片到canvas
        context.drawImage(img, 0, 0);

        // 获取图像数据
        const imageData = context.getImageData(
          0,
          0,
          canvas.width,
          canvas.height
        );

        // 使用jsQR解析二维码
        const code = jsQR(imageData.data, imageData.width, imageData.height);

        uni.hideLoading();

        if (code) {
          this.handleScanSuccess(code.data);
        } else {
          uni.showToast({
            title: "未识别到二维码",
            icon: "none",
          });
        }
      };

      img.onerror = () => {
        uni.hideLoading();
        uni.showToast({
          title: "图片加载失败",
          icon: "none",
        });
      };

      img.src = imagePath;
    },
    // #endif

    // #ifdef MP-WEIXIN
    /**
     * 微信小程序扫码
     */
    startScan() {
      const app = this;
      uni.scanCode({
        scanType: ["qrCode", "barCode"],
        success(res) {
          app.handleScanSuccess(res.result);
        },
        fail(err) {
          if (err.errMsg.includes("cancel")) {
            return;
          }
          uni.showToast({
            title: "扫码失败，请重试",
            icon: "none",
          });
        },
      });
    },
    // #endif

    /**
     * 处理扫码成功
     */
    handleScanSuccess(result) {

      // 停止扫码
      this.isScanning = false;
      // #ifdef H5
      this.stopCamera();
      // #endif

      // 震动反馈
      uni.vibrateShort();

      // 播放成功提示音
      uni.showToast({
        title: "扫码成功",
        icon: "success",
        duration: 1500,
      });

      if (this.scanType === "rental") {
        return uni.navigateTo({
          url: `/pages/newpayment/index?code=${encodeURIComponent(
            // this.scanResult/
            result.split("kpl/")?.[1]
          )}&type=rental`,
        });
      } else {
        // 跳转到订单详情页面
        return uni.navigateTo({
          url: `/pages/newreturn/index?code=${encodeURIComponent(
            // this.scanResult
            result.split("kpl/")?.[1]
          )}&type=return`,
        });
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.scan-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background: #000000;
  display: flex;
  flex-direction: column;
}

// H5扫码区域
.h5-scan-area,
.mp-scan-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  position: relative;
}

// 相机预览
.camera-preview {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1;

  .video-preview {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }

  .scan-canvas {
    position: absolute;
    top: -9999px;
    left: -9999px;
    visibility: hidden;
  }
}

// 扫码框
.scan-frame {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 2;

  .scan-box {
    width: 500rpx;
    height: 500rpx;
    position: relative;

    // 四个角的装饰
    .corner {
      position: absolute;
      width: 60rpx;
      height: 60rpx;
      border: 6rpx solid #74b9ff;

      &.corner-tl {
        top: 0;
        left: 0;
        border-right: none;
        border-bottom: none;
      }

      &.corner-tr {
        top: 0;
        right: 0;
        border-left: none;
        border-bottom: none;
      }

      &.corner-bl {
        bottom: 0;
        left: 0;
        border-right: none;
        border-top: none;
      }

      &.corner-br {
        bottom: 0;
        right: 0;
        border-left: none;
        border-top: none;
      }
    }

    // 扫描线
    .scan-line {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 4rpx;
      background: linear-gradient(90deg, transparent, #74b9ff, transparent);
      animation: scan-animation 2s linear infinite;
    }
  }

  .scan-hint {
    color: #ffffff;
    font-size: 32rpx;
    text-align: center;
    margin-top: 60rpx;
    opacity: 0.8;
  }
}

// 扫描动画
@keyframes scan-animation {
  0% {
    top: 0;
  }

  100% {
    top: calc(100% - 4rpx);
  }
}

// 小程序扫码图标
.scan-icon {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  opacity: 0.6;
}

// 底部操作按钮
.scan-actions {
  position: absolute;
  bottom: 100rpx;
  left: 0;
  right: 0;
  display: flex;
  justify-content: space-around;
  padding: 0 40rpx;
  z-index: 3;

  .action-btn {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 20rpx;

    .btn-icon {
      width: 100rpx;
      height: 100rpx;
      background: rgba(116, 185, 255, 0.3);
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-bottom: 16rpx;
    }

    .btn-text {
      color: #ffffff;
      font-size: 24rpx;
      text-align: center;
    }
  }

  // 小程序按钮样式
  .scan-button,
  .back-button {
    width: 300rpx;
    height: 100rpx;
    border-radius: 50rpx;
    display: flex;
    align-items: center;
    justify-content: center;

    .btn-text {
      font-size: 32rpx;
      font-weight: 600;
    }
  }

  .scan-button {
    background: linear-gradient(135deg, #74b9ff 0%, #0984e3 100%);

    .btn-text {
      color: #ffffff;
    }
  }

  .back-button {
    background: rgba(255, 255, 255, 0.2);
    border: 1px solid rgba(255, 255, 255, 0.3);

    .btn-text {
      color: #ffffff;
    }
  }
}
</style>
